package com.myrice.jms.impl;

import java.io.IOException;
import java.nio.channels.ByteChannel;
import java.nio.channels.SelectableChannel;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;

import com.myrice.core.Connection;
import com.myrice.core.Session;
import com.myrice.core.impl.DefaultConnector;
import com.myrice.core.impl.DefaultMessageReader;
import com.myrice.core.impl.DefaultMessageWriter;
import com.myrice.core.impl.DefaultNotifier;

public class DefaultMsgConnector extends DefaultConnector<Connection, Session> {
	protected DefaultMsgServerHandler handler;

	public DefaultMsgConnector() throws IOException {
		this.handler = createHandler();
	}

	public DefaultMsgConnector(DefaultMsgServerHandler handler)
			throws IOException {
		this.handler = handler;
		this.notifier.addHandler(this.handler);
	}

	public DefaultMsgConnector(ExecutorService execute, Executor reader,
			Executor writer) throws IOException {
		super(execute, new DefaultNotifier<Connection, Session>(),
				new DefaultMessageReader<Connection, Session>(reader),
				new DefaultMessageWriter<Connection, Session>(writer));
		this.handler = createHandler();
	}

	protected DefaultMsgServerHandler createHandler() {
		return new DefaultMsgServerHandler(this);
	}

	public DefaultMsgSession getHandle(ByteChannel sc) {
		return handler.getHandle(sc);
	}

	public DefaultMsgServerHandler getServerHandler() {
		return this.handler;
	}

	public void registor2wait(ByteChannel sc, Connection conn) {
		registor((SelectableChannel) sc, conn);
		for (int i = 0; i < 1000 && getHandle(sc) == null; i++)
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	}
}
